package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"NicePay/utils"
	"github.com/dgrijalva/jwt-go"
	"errors"
)

// before all handler contain Authorization
var JWTVerify = gin.HandlerFunc(func(ctx *gin.Context) {
	// If jwt token exist
	jwtToken := ctx.Query("token")
	//log.Println(jwtToken)
	if len(jwtToken) == 0 {
		ctx.AbortWithStatus(http.StatusUnauthorized)
		return
	}
	// If jwt token valid
	claims, err := decodeJWT(jwtToken, utils.GetConfig().GlobalToken)
	if err != nil || claims["uid"] == nil {
		ctx.AbortWithStatus(http.StatusUnauthorized)
		return
	}
	ctx.Set("uid", uint(claims["uid"].(float64)))
})

func decodeJWT(jwtKey string, signedKey string) (jwt.MapClaims, error) {
	token, err := jwt.Parse(jwtKey, func(token *jwt.Token) (interface{}, error) {
		// Don't forget to validate the alg is what you expect:
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			str := "Unexpected signing method: " + token.Header["alg"].(string)
			return nil, errors.New(str)
		}
		// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
		return []byte(signedKey), nil
	})
	if token != nil && token.Claims != nil {
		if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
			return claims, nil
		}
	}
	return nil, err
}
